import axios from 'axios'
import { cloneDeep } from 'lodash'
import { regionNums } from '@/utils/buildingRegionEnum'
import {
  getLayerSourceByType,
  getSpecialRegionArea,
  queryChoiceBuild,
  queryQuestion,
} from '@/api/question'
import { closeLoading, showLoading } from '@/utils/loading'
import { group } from '@/utils/radash'
import { queryNewBuild, queryPoint } from '@/api/building'
import { specialInfoTable } from '@/views/one-map/left-community-info/build-edit-config'

export function useOldBuilding() {
  let map = null
  let buildingSource
  let buildingQuestionInfo

  const init = (_map) => {
    map = _map
  }

  let legendArr = null

  const _buildingLayerIds = []
  const _highlightBuildingLayerIds = []
  let _totalArr = {}
  let _totalArrGroup = {}
  let _totalArrGroupNew = {}
  let _tempHistoryArr = {}
  let _tempHistoryIds
  let _tempUpdateArr = {}
  let _tempUpdateIds

  const findQuestionMap = {}

  const _addedBuilding = []

  // 添加服务图层
  const addSourceLayer = (
    map,
    styleJson,
    params,
    ids = {
      serious: [],
      medium: [],
      controlled: [],
      noLevel: [],
    },
    historyIds = [],
    updateIds = []
  ) => {
    Object.keys(styleJson.sources).forEach((sourceKey) => {
      if (!map.getSource(sourceKey)) {
        map.addSource(sourceKey, styleJson.sources[sourceKey])
      }
    })
    styleJson.layers.forEach((layer) => {
      // 设置白膜颜色为白色，方便显示
      // layer.paint["fill-extrusion-color"] = "#FFFFFF";
      // layer.paint["fill-extrusion-height"] = 0;
      if (
        ids.serious?.length ||
        ids.medium?.length ||
        ids.controlled?.length ||
        ids.noLevel?.length ||
        historyIds?.length ||
        updateIds?.length
      ) {
        layer.paint['fill-color'] = [
          'case',
          ['in', ['get', 'JZWBM'], ['literal', ids.serious]],
          '#FF0B0B',
          ['in', ['get', 'JZWBM'], ['literal', ids.medium]],
          '#F7931B',
          ['in', ['get', 'JZWBM'], ['literal', ids.controlled]],
          '#F7EC2F',
          ['in', ['get', 'JZWBM'], ['literal', ids.noLevel]],
          '#B886F8',
          ['in', ['get', 'JZWBM'], ['literal', historyIds]],
          '#0f0',
          ['in', ['get', 'JZWBM'], ['literal', updateIds]],
          '#ff0',
          'rgba(255,255,255,0.4)',
        ]
      } else {
        layer.paint['fill-color'] = 'rgba(255,255,255,0.4)'
      }

      layer.paint['fill-outline-color'] = 'rgba(255,255,255,0.4)'

      if (regionNums[params.regionName]) {
        if (layer.filter) {
          layer.filter = [
            'all',
            layer.filter,
            ['==', 'QXMC', regionNums[params.regionName]],
          ]
        } else {
          layer.filter = ['all', ['==', 'QXMC', regionNums[params.regionName]]]
        }
      }

      if (params.isStreet) {
        if (layer.filter) {
          layer.filter = [
            'all',
            layer.filter,
            ['in', ['get', 'JZWBM'], ['literal', ids]],
          ]
        } else {
          layer.filter = ['all', ['in', ['get', 'JZWBM'], ['literal', ids]]]
        }
      }

      const highlightLayer = cloneDeep(layer)
      highlightLayer.id = highlightLayer.id + '_highlight'
      if (params.isStreet) {
        const length = highlightLayer.filter.length
        highlightLayer.filter[length - 1] = ['in', 'JZWBM', '']
      } else {
        if (highlightLayer.filter) {
          highlightLayer.filter = [
            'all',
            highlightLayer.filter,
            ['in', 'JZWBM', ''],
          ]
        } else {
          highlightLayer.filter = ['all', ['in', 'JZWBM', '']]
        }
      }
      // highlightLayer.paint["fill-extrusion-color"] = "#FF0000";
      // highlightLayer.paint["fill-extrusion-height"] = 0;
      highlightLayer.paint['fill-color'] = 'rgb(0,0,255)'
      highlightLayer.paint['fill-outline-color'] = 'rgb(0,0,255)'

      _buildingLayerIds.push(layer.id)
      _highlightBuildingLayerIds.push(highlightLayer.id)

      if (!map.getLayer(layer.id)) {
        map.addLayer(layer)
      }
      if (!map.getLayer(highlightLayer.id)) {
        map.addLayer(highlightLayer)
      }
    })
  }

  // const getSimpleFilter = (ids, historyIds, updateIds) => {
  //   const { serious, medium, controlled, noLevel } = ids
  //
  //   // 从后面的数组中排除前面数组的ID
  //   const uniqueSerious = serious
  //   const uniqueMedium = medium.filter((id) => !uniqueSerious.includes(id))
  //   const uniqueControlled = controlled.filter(
  //     (id) => !uniqueSerious.includes(id) && !uniqueMedium.includes(id)
  //   )
  //   const uniqueNoLevel = noLevel.filter(
  //     (id) =>
  //       !uniqueSerious.includes(id) &&
  //       !uniqueMedium.includes(id) &&
  //       !uniqueControlled.includes(id)
  //   )
  //   const uniqueHistoryIds = historyIds.filter(
  //     (id) =>
  //       !uniqueSerious.includes(id) &&
  //       !uniqueMedium.includes(id) &&
  //       !uniqueControlled.includes(id) &&
  //       !uniqueNoLevel.includes(id)
  //   )
  //   const uniqueUpdateIds = updateIds.filter(
  //     (id) =>
  //       !uniqueSerious.includes(id) &&
  //       !uniqueMedium.includes(id) &&
  //       !uniqueControlled.includes(id) &&
  //       !uniqueNoLevel.includes(id) &&
  //       !uniqueHistoryIds.includes(id)
  //   )
  //
  //   // 更新筛选条件
  //   return [
  //     'case',
  //     ['in', ['get', 'JZWBM'], ['literal', uniqueSerious]],
  //     '#FF0B0B',
  //     ['in', ['get', 'JZWBM'], ['literal', uniqueMedium]],
  //     '#F7931B',
  //     ['in', ['get', 'JZWBM'], ['literal', uniqueControlled]],
  //     '#F7EC2F',
  //     ['in', ['get', 'JZWBM'], ['literal', uniqueNoLevel]],
  //     '#B886F8',
  //     ['in', ['get', 'JZWBM'], ['literal', uniqueHistoryIds]],
  //     '#0f0',
  //     ['in', ['get', 'JZWBM'], ['literal', uniqueUpdateIds]],
  //     '#ff0', // 新增颜色
  //     'rgba(255,255,255,0.4)',
  //   ]
  // }

  const getBuildingServiceSource = async () => {
    if (buildingSource) {
      return buildingSource
    }
    try {
      const res = await axios.get(window.buildingServiceUrl)
      if (res.status === 200) {
        buildingSource = res.data
        return res.data
      } else {
        return null
      }
    } catch (e) {
      console.log(e)
      return null
    }
  }

  const findNodeById = (id, data, isParent) => {
    let length = data.length
    for (let i = 0; i < length; i++) {
      const item = data[i]
      if (item.pkid === id) {
        const orderIndex = item.orderIndex
        if (orderIndex === 0 || isParent) {
          return item
        } else {
          return data.find((f) => f.orderIndex === orderIndex - 1)
        }
      } else if (item.problemInfoList) {
        const result = findNodeById(id, item.problemInfoList, isParent)
        if (result) {
          return result
        }
      } else if (item.children) {
        const result = findNodeById(id, item.children, isParent)
        if (result) {
          return result
        }
      }
    }
    return null
  }

  const findQuestionById = async (id, isParent) => {
    const questionInfo = await getQuestionInfo()
    if (!findQuestionMap[id]) {
      findQuestionMap[id] = findNodeById(id, questionInfo, isParent)
    }
    return findQuestionMap[id]
  }

  const getQuestionInfo = async () => {
    if (buildingQuestionInfo) {
      return buildingQuestionInfo
    }
    try {
      const res = await queryQuestion({
        templateType: 'build',
      })
      if (res.success) {
        buildingQuestionInfo = res.data
        return res.data
      }
    } catch (e) {
      console.log(e)
      return []
    }
  }

  const setBuildingHighlight = (ids) => {
    _highlightBuildingLayerIds.forEach((layerId) => {
      if (map.getLayer(layerId)) {
        map.setFilter(layerId, ['in', 'JZWBM', ...ids])
      }
    })
  }

  const getTotalArr = (data) => {
    const result = {}
    data.forEach((item) => {
      let info = {
        areaName: item.areaName,
        name: item.name,
        problemId: item.problemId,
        residenceId: item.residenceId,
      }

      item.content.forEach((contentItem) => {
        contentItem.buildings.forEach((building) => {
          if (!result[building]) {
            result[building] = []
          }
          const f = result[building].find(
            (item) =>
              item.problemId === info.problemId &&
              item.residenceId === info.residenceId
          )
          if (!f) {
            result[building].push(info)
          }
        })
      })
    })
    return result
  }

  const groupInfoByProblem = (data) => {
    const obj = group(data, (f) => f.problemId)
    const problemIds = Object.keys(obj)
    const length = problemIds.length
    const result = {}
    for (let i = 0; i < length; i++) {
      const item = obj[problemIds[i]]
      const ids = []
      if (item) {
        const len = item.length
        for (let j = 0; j < len; j++) {
          const val = item[j]
          const { content } = val
          if (content) {
            const length = content.length
            for (let m = 0; m < length; m++) {
              const val = content[m]
              val.buildings.forEach((building) => {
                ids.push(building)
              })
            }
          }
        }
      }
      result[problemIds[i]] = [...new Set(ids)]
    }
    _totalArrGroup = result
  }

  const findProblemInfoList = (data) => {
    return data.map((item) => {
      if (item.problemInfoList) {
        return {
          label: item.name,
          value: item.pkid,
          children: item.problemInfoList
            .map((item) => {
              return item.children.map((i) => i.pkid)
            })
            .flat(),
        }
      } else {
        if (item.children) {
          const res = findProblemInfoList(item.children)
          if (res) {
            return res
          }
        }
      }
    })
  }

  const getLegendArr = async () => {
    if (legendArr) {
      return legendArr
    }
    // let res = await getQuestionInfo()
    // if (res?.length) {
    //   const data = findProblemInfoList(res[0].children)
    //   if (data?.length) {
    //     const list = data.flat()
    //     if (list?.length) {
    //       legendArr = list
    //     }
    //   }
    // }
    legendArr = Object.keys(_totalArrGroupNew).map((val, index) => {
      return {
        label: val,
        value: index + '',
      }
    })
    return legendArr
  }

  const changeLegend = (checkList) => {
    // const problemIds = []
    // checkList.forEach((item) => {
    //   const val = legendArr?.find((f) => f.value === item)
    //   if (val && item !== 'history-range' && item !== 'update-range') {
    //     problemIds.push(...val.children)
    //   }
    // })
    // const buildingIds = []
    // problemIds.forEach((id) => {
    //   const val = _totalArrGroup[id]
    //   if (val) {
    //     buildingIds.push(...val)
    //   }
    // })
    // const ids = [...new Set(buildingIds)]
    const len = checkList.length
    let ids = {
      serious: [],
      medium: [],
      controlled: [],
      noLevel: [],
    }
    const keys = Object.keys(_totalArrGroupNew)
    for (let i = 0; i < len; i++) {
      const children = _totalArrGroupNew[keys[checkList[i]]]
      if (!children) continue
      children.forEach((item) => {
        const color = item.color
        if (color === '#FF0B0B') {
          ids.serious.push(item.pkid)
        } else if (color === '#F7931B') {
          ids.medium.push(item.pkid)
        } else if (color === '#F7EC2F') {
          ids.controlled.push(item.pkid)
        } else {
          ids.noLevel.push(item.pkid)
        }
      })
    }
    ids = {
      serious: [...new Set(ids.serious)],
      medium: [...new Set(ids.medium)],
      controlled: [...new Set(ids.controlled)],
      noLevel: [...new Set(ids.noLevel)],
    }
    let historyIds = []
    if (checkList.includes('history-range')) {
      historyIds = _tempHistoryIds
    }
    let updateIds = []
    if (checkList.includes('update-range')) {
      updateIds = _tempUpdateIds
    }
    filterBuildingLayer('oldBuilding', ids, historyIds, updateIds, true)
  }

  const getBuildingDetailInfo = async (id) => {
    const item = _totalArr[id]
    const result = []
    if (item) {
      const val = group(item, (f) => f.residenceId)
      const data = Object.keys(val)
      const length = data.length
      for (let i = 0; i < length; i++) {
        const key = data[i]
        const v = val[key]
        if (v?.length) {
          const name = v[0].areaName + v[0].name
          const id = v[0].residenceId
          const children = []
          const len = v.length
          for (let j = 0; j < len; j++) {
            const item = v[j]
            const f = await findQuestionById(item.problemId)
            let question = ''
            if (f) {
              const templateId = f.templateId
              const parent = await findQuestionById(templateId, true)
              if (parent) {
                question = parent.name + ': ' + f.problemContent
              } else {
                question = f.problemContent
              }
            }
            children.push({
              question,
            })
          }
          result.push({
            name,
            id,
            children: [children],
          })
        }
      }
    }
    return result
  }

  const getOtherBuildingDetailInfo = async (id, type, map) => {
    const result = []
    const item = map[id]
    if (item) {
      const val = group(item, (f) => f.residenceId)
      const data = Object.keys(val)
      const length = data.length
      for (let i = 0; i < length; i++) {
        const key = data[i]
        const v = val[key]
        if (v?.length) {
          const name = v[0].areaName + v[0].name
          const id = v[0].residenceId
          const children = [
            {
              question: type === 'history' ? '历史建筑:' : '更新建筑:',
            },
          ]
          result.push({
            name,
            id,
            children: [children],
          })
        }
      }
    }
    return result
  }

  const getDetailInfo = async (id) => {
    const len = _addedBuilding.length
    let result = []
    let type
    for (let i = 0; i < len; i++) {
      const item = _addedBuilding[i]
      if (item === 'oldBuilding') {
        // type = 'building'
        // result = await getBuildingDetailInfo(id)
      } else if (item === 'history') {
        type = 'history'
        result = await getOtherBuildingDetailInfo(id, type, _tempHistoryArr)
      } else {
        type = 'update'
        result = await getOtherBuildingDetailInfo(id, type, _tempUpdateArr)
      }
      if (result.length) {
        break
      }
    }
    return {
      type,
      result,
    }
  }

  const getChoiceBuildings = async (params) => {
    if (Object.keys(_totalArrGroupNew).length > 0) {
      let ids = {
        serious: [],
        medium: [],
        controlled: [],
        noLevel: [],
      }
      Object.values(_totalArrGroupNew).map((val) => {
        // 这里的val是题目
        val.forEach((item) => {
          const color = item.color
          if (color === '#FF0B0B') {
            ids.serious.push(item.pkid)
          } else if (color === '#F7931B') {
            ids.medium.push(item.pkid)
          } else if (color === '#F7EC2F') {
            ids.controlled.push(item.pkid)
          } else {
            ids.noLevel.push(item.pkid)
          }
        })
      })
      ids = {
        serious: [...new Set(ids.serious)],
        medium: [...new Set(ids.medium)],
        controlled: [...new Set(ids.controlled)],
        noLevel: [...new Set(ids.noLevel)],
      }
      return ids
    }
    try {
      const res = await queryNewBuild(params)
      if (res.success) {
        const result = {}
        let ids = {
          serious: [],
          medium: [],
          controlled: [],
          noLevel: [],
        }
        const length = specialInfoTable.length
        const len = res.data.length
        for (let i = 0; i < length; i++) {
          const item = specialInfoTable[i]
          const title = item.title.split('、')[1]
          if (!result[title]) {
            result[title] = []
          }
          const hasItemKey = item.questions[0].prop
          const levelItem = item.questions.find((i) =>
            i.prop?.includes('Level')
          )
          for (let j = 0; j < len; j++) {
            const dataItem = res.data[j]
            const hasItem = dataItem[hasItemKey]
            if (hasItem === 1) {
              let color = '#B886F8'
              if (levelItem) {
                const levelKey = levelItem.prop
                const level = dataItem[levelKey]
                if (level.includes('严重')) {
                  color = '#FF0B0B'
                  ids.serious.push(dataItem.pkid)
                } else if (level.includes('中等')) {
                  color = '#F7931B'
                  ids.medium.push(dataItem.pkid)
                } else if (level.includes('可控')) {
                  color = '#F7EC2F'
                  ids.controlled.push(dataItem.pkid)
                } else {
                  ids.noLevel.push(dataItem.pkid)
                }
              }
              result[title].push({
                pkid: dataItem.pkid,
                color,
              })
            }
          }
        }
        _totalArrGroupNew = result
        ids = {
          serious: [...new Set(ids.serious)],
          medium: [...new Set(ids.medium)],
          controlled: [...new Set(ids.controlled)],
          noLevel: [...new Set(ids.noLevel)],
        }
        return ids
      }
    } catch (e) {
      return {
        serious: [],
        medium: [],
        controlled: [],
        noLevel: [],
      }
    }
    return {
      serious: [],
      medium: [],
      controlled: [],
      noLevel: [],
    }
  }

  const _getChoiceBuildings = async (params) => {
    if (Object.keys(_totalArrGroup).length > 0) {
      const buildingIds = []
      Object.values(_totalArrGroup).map((val) => {
        buildingIds.push(...val)
      })
      return [...new Set(buildingIds)]
    }
    try {
      // const obj = {
      //   ...params,
      //   regionId: '',
      //   streetId: '',
      //   communityId: '',
      // }
      const res = await queryChoiceBuild(params)
      if (res.success) {
        const result = []
        const totalData = []
        res.data.forEach((item) => {
          try {
            const content = JSON.parse(item.content)
            if (content) {
              // console.log(content)
              content.forEach((val) => {
                result.push(...val.buildings)
              })
              totalData.push({
                content,
                areaName: item.areaname,
                name: item.name,
                problemId: item.problem_id,
                residenceId: item.business_id,
              })
            }
          } catch (e) {
            // console.log(item.business_id, item.problem_id)
            try {
              const content = item.content.replaceAll(',]', ']')
              // console.log(content)
              const str = JSON.parse(content)
              if (str) {
                str.forEach((val) => {
                  result.push(...val.buildings)
                })
                totalData.push({
                  content,
                  areaName: item.areaname,
                  name: item.name,
                  problemId: item.problem_id,
                  residenceId: item.business_id,
                })
              }
            } catch (e) {
              console.log(e)
            }
          }
        })
        _totalArr = getTotalArr(totalData)
        groupInfoByProblem(totalData)
        return [...new Set(result)]
      } else {
        return []
      }
    } catch (e) {
      console.log(e)
      return []
    }
  }

  // 废弃
  const addOldBuilding = async (params) => {
    showLoading()
    // 先获取全部的服务图层
    const source = await getBuildingServiceSource()
    // 根据筛选获取选中的建筑物
    const ids = await getChoiceBuildings(params)
    // console.log(ids)
    if (source) {
      // 根据选中的建筑物添加图层
      addSourceLayer(map, source, params, ids)
    }
    closeLoading()
  }

  const getHistoryBuilding = async (params) => {
    if (_tempHistoryIds) {
      return _tempHistoryIds
    }
    try {
      const res = await getLayerSourceByType('region', params)
      if (res.success) {
        const { historyBuildRange } = res.data || {}
        if (historyBuildRange) {
          const result = []
          const totalData = []
          historyBuildRange.forEach((item) => {
            try {
              const content = JSON.parse(item.content)
              if (content) {
                // console.log(content)
                content.forEach((val) => {
                  result.push(...val.buildings)
                })
                totalData.push({
                  content,
                  areaName: item.area_name,
                  name: item.name,
                  problemId: item.pkid,
                  residenceId: item.pkid,
                })
              }
            } catch (e) {
              // console.log(item.business_id, item.problem_id)
              try {
                const content = item.content.replaceAll(',]', ']')
                // console.log(content)
                const str = JSON.parse(content)
                if (str) {
                  str.forEach((val) => {
                    result.push(...val.buildings)
                  })
                  totalData.push({
                    content,
                    areaName: item.area_name,
                    name: item.name,
                    problemId: item.pkid,
                    residenceId: item.pkid,
                  })
                }
              } catch (e) {
                console.log(e)
              }
            }
          })
          _tempHistoryArr = getTotalArr(totalData)
          _tempHistoryIds = [...new Set(result)]
          return _tempHistoryIds
        }
      }
    } catch (e) {
      console.log(e)
      return []
    }
  }

  const getUpdateBuilding = async (params) => {
    if (_tempUpdateIds) {
      return _tempUpdateIds
    }
    try {
      const res = await getSpecialRegionArea('', params)
      if (res.success) {
        const { businessUpdateRange } = res.data || []
        if (businessUpdateRange) {
          const result = []
          const totalData = []
          businessUpdateRange.forEach((item) => {
            try {
              const content = JSON.parse(item.content)
              if (content) {
                // console.log(content)
                content.forEach((val) => {
                  result.push(...val.buildings)
                })
                totalData.push({
                  content,
                  areaName: item.area_name,
                  name: item.name,
                  problemId: item.pkid,
                  residenceId: item.pkid,
                })
              }
            } catch (e) {
              // console.log(item.business_id, item.problem_id)
              try {
                const content = item.content.replaceAll(',]', ']')
                // console.log(content)
                const str = JSON.parse(content)
                if (str) {
                  str.forEach((val) => {
                    result.push(...val.buildings)
                  })
                  totalData.push({
                    content,
                    areaName: item.area_name,
                    name: item.name,
                    problemId: item.pkid,
                    residenceId: item.pkid,
                  })
                }
              } catch (e) {
                console.log(e)
              }
            }
          })
          _tempUpdateArr = getTotalArr(totalData)
          _tempUpdateIds = [...new Set(result)]
          return _tempUpdateIds
        }
      }
    } catch (e) {
      console.log(e)
      return []
    }
  }

  const filterBuildingLayer = (
    type,
    ids,
    historyIds,
    updateIds,
    replace = false
  ) => {
    const len = _buildingLayerIds.length
    for (let i = 0; i < len; i++) {
      const layerId = _buildingLayerIds[i]
      if (!replace) {
        const currentFilter = map.getPaintProperty(layerId, 'fill-color')
        if (Array.isArray(currentFilter)) {
          if (type === 'oldBuilding') {
            historyIds = currentFilter[9][2][1] || []
            updateIds = currentFilter[11][2][1] || []
          } else if (type === 'history') {
            ids = {
              serious: currentFilter[1][2][1] || [],
              medium: currentFilter[3][2][1] || [],
              controlled: currentFilter[5][2][1] || [],
              noLevel: currentFilter[7][2][1] || [],
            }
            updateIds = currentFilter[11][2][1] || []
          } else {
            ids = {
              serious: currentFilter[1][2][1] || [],
              medium: currentFilter[3][2][1] || [],
              controlled: currentFilter[5][2][1] || [],
              noLevel: currentFilter[7][2][1] || [],
            }
            historyIds = currentFilter[9][2][1] || []
          }
        } else {
          if (type === 'oldBuilding') {
            historyIds = []
            updateIds = []
          } else if (type === 'history') {
            ids = {
              serious: [],
              medium: [],
              controlled: [],
              noLevel: [],
            }
            updateIds = []
          } else {
            ids = {
              serious: [],
              medium: [],
              controlled: [],
              noLevel: [],
            }
            historyIds = []
          }
        }
      }
      map.setPaintProperty(layerId, 'fill-color', [
        'case',
        ['in', ['get', 'JZWBM'], ['literal', ids.serious]],
        '#FF0B0B',
        ['in', ['get', 'JZWBM'], ['literal', ids.medium]],
        '#F7931B',
        ['in', ['get', 'JZWBM'], ['literal', ids.controlled]],
        '#F7EC2F',
        ['in', ['get', 'JZWBM'], ['literal', ids.noLevel]],
        '#B886F8',
        ['in', ['get', 'JZWBM'], ['literal', historyIds]],
        '#0f0',
        ['in', ['get', 'JZWBM'], ['literal', updateIds]],
        '#ff0',
        'rgba(255,255,255,0.4)',
      ])
    }
  }

  const addBuilding = async (params, type) => {
    if (_addedBuilding.includes(type)) return
    showLoading()
    if (_buildingLayerIds.length) {
      try {
        let historyIds
        let updateIds
        let ids = {
          serious: [],
          medium: [],
          controlled: [],
          noLevel: [],
        }
        switch (type) {
          case 'oldBuilding': {
            ids = await getChoiceBuildings(params)
            break
          }
          case 'history': {
            historyIds = await getHistoryBuilding(params)
            break
          }
          case 'update': {
            updateIds = await getUpdateBuilding(params)
            break
          }
        }
        filterBuildingLayer(type, ids, historyIds, updateIds)
      } catch (e) {
        console.log(e)
      }
    } else {
      // 不存在就加载服务图层
      const source = await getBuildingServiceSource()
      if (source) {
        switch (type) {
          case 'oldBuilding': {
            // 根据筛选获取选中的建筑物
            const ids = await getChoiceBuildings(params)
            addSourceLayer(map, source, params, ids)
            break
          }
          case 'history': {
            const historyIds = await getHistoryBuilding(params)
            addSourceLayer(map, source, params, undefined, historyIds)
            break
          }
          case 'update': {
            const updateIds = await getUpdateBuilding(params)
            // console.log(updateIds)
            addSourceLayer(map, source, params, undefined, [], updateIds)
            break
          }
        }
      }
    }
    _addedBuilding.push(type)
    closeLoading()
  }

  const removeBuilding = (type) => {
    if (!_addedBuilding.includes(type)) return
    if (_buildingLayerIds.length) {
      let historyIds = []
      let updateIds = []
      let ids = {
        serious: [],
        medium: [],
        controlled: [],
        noLevel: [],
      }
      // 没传replace时，是根据type读取的，所以直接空数组
      filterBuildingLayer(type, ids, historyIds, updateIds)
    }
    const index = _addedBuilding.findIndex((i) => i === type)
    if (index !== -1) {
      _addedBuilding.splice(index, 1)
    }
  }

  const removeOldBuilding = () => {
    _buildingLayerIds.forEach((layerId) => {
      if (map.getLayer(layerId)) {
        map.removeLayer(layerId)
      }
    })
    _highlightBuildingLayerIds.forEach((layerId) => {
      if (map.getLayer(layerId)) {
        map.removeLayer(layerId)
      }
    })
    _addedBuilding.length = 0
    _buildingLayerIds.length = 0
    _highlightBuildingLayerIds.length = 0
  }

  const getPointsServiceSource = async (params) => {
    const features = []
    try {
      const res = await queryPoint(params)
      if (res.success) {
        res.data?.map((item) => {
          if (!item.point) return
          const feature = {
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: JSON.parse(item.point),
            },
            properties: {
              pkid: item.pkid,
            },
          }
          features.push(feature)
        })
      }
    } catch (e) {
      console.log(e)
    }
    return {
      type: 'FeatureCollection',
      features: features,
    }
  }

  const _getPointsServiceSource = async (params) => {
    const features = []
    try {
      // const obj = {
      //   ...params,
      //   regionId: '',
      //   streetId: '',
      //   communityId: '',
      // }
      const res = await queryChoiceBuild(params)
      if (res.success) {
        const length = res.data.length
        for (let i = 0; i < length; i++) {
          const item = res.data[i]
          try {
            const content = JSON.parse(item.content)
            if (content) {
              const len = content.length
              for (let j = 0; j < len; j++) {
                const val = content[j]
                if (val.points?.length) {
                  const f = await findQuestionById(item.problem_id)
                  let question = ''
                  if (f) {
                    const templateId = f.templateId
                    const parent = await findQuestionById(templateId, true)
                    if (parent) {
                      question = parent.name + ': ' + f.problemContent
                    } else {
                      question = f.problemContent
                    }
                  }
                  const feature = {
                    type: 'Feature',
                    geometry: {
                      type: 'MultiPoint',
                      coordinates: val.points,
                    },
                    properties: {
                      名称: item.name,
                      问题: question,
                      residenceId: item.business_id,
                    },
                  }
                  features.push(feature)
                }
              }
            }
          } catch (e) {
            // console.log(item.business_id, item.problem_id)
            try {
              const content = item.content.replaceAll(',]', ']')
              // console.log(content)
              const str = JSON.parse(content)
              if (str) {
                const len = str.length
                for (let j = 0; j < len; j++) {
                  const val = str[j]
                  if (val.points?.length) {
                    const f = await findQuestionById(item.problem_id)
                    let question = ''
                    if (f) {
                      const templateId = f.templateId
                      const parent = await findQuestionById(templateId, true)
                      if (parent) {
                        question = parent.name + ': ' + f.problemContent
                      } else {
                        question = f.problemContent
                      }
                    }
                    const feature = {
                      type: 'Feature',
                      geometry: {
                        type: 'MultiPoint',
                        coordinates: val.points,
                      },
                      properties: {
                        名称: item.name,
                        问题: question,
                        residenceId: item.business_id,
                      },
                    }
                    features.push(feature)
                  }
                }
              }
            } catch (e) {
              console.log(e)
            }
          }
        }
      }
    } catch (e) {
      console.log(e)
    }
    return {
      type: 'FeatureCollection',
      features,
    }
  }

  const resetTempIds = () => {
    _totalArr = {}
    _totalArrGroup = {}
    _totalArrGroupNew = {}
    _tempHistoryArr = {}
    _tempHistoryIds = null
    _tempUpdateArr = {}
    _tempUpdateIds = null
  }

  return {
    buildingLayerIds: _buildingLayerIds,
    init,
    addOldBuilding,
    addBuilding,
    removeBuilding,
    removeOldBuilding,
    getDetailInfo,
    setBuildingHighlight,
    getPointsServiceSource,
    getLegendArr,
    changeLegend,
    resetTempIds,
  }
}
